<template>
	<uni-popup ref="popup" type="center">
		<view class="c-sign">
			<view class="opts" :style="{width: leftOptsWidth + 'px'}">
				<view class="opts_btn" @click="close">关闭</view>
				<view class="opts_btn" @click="clear">清除</view>
				<view class="opts_btn opts_btn--confirm" @click="save">确认</view>
			</view>
			<view class="canvas-wrap" :style="{paddingTop: topHeight + 'px'}">
				<canvas class="canvas" disable-scroll="true" :style="{'width':width+'px','height':height+'px'}"
					canvas-id="designature" id="designature" @touchstart="starts" @touchmove="moves"></canvas>
				<canvas class="canvasImg" :style="{'width':height+'px','height':width+'px'}" canvas-id="designature2"
					id="designature2"></canvas>
			</view>
		</view>
	</uni-popup>
</template>

<script>
	import { baseURL } from '@/utils/request.js'
	import crypto from '@/utils/crypto'

	const app = getApp()
	const global = app.globalData

	export default {
		data() {
			return {
				// 左侧操作区域的宽
				leftOptsWidth: 60,
				// 顶部的宽（状态栏和导航栏）
				topHeight: 0,
				ctx: null,
				ctx2: null,
				line: [],
				width: 0,
				height: 0,
				radius: 0,
				isSign: false, //判断是否已经签字
			}
		},
		created() {
			const { pageHeight, pageWidth, statusHeight, navHeight, IosArea } = global
			this.topHeight = statusHeight + navHeight
			this.width = pageWidth - this.leftOptsWidth
			this.height = pageHeight - statusHeight - navHeight - IosArea
			uni.$off('openSignPopup');
			uni.$on('openSignPopup', this.open)
		},
		methods: {
			open() {
				this.$refs.popup.open()
				this.ctx = uni.createCanvasContext('designature', this);
				this.ctx2 = uni.createCanvasContext('designature2', this);
				this.drawBgColor()
			},
			close() {
				this.$refs.popup.close()
			},
			drawBgColor() {
				const bgColor = '#fff'
				this.ctx.setFillStyle(bgColor)
				this.ctx.fillStyle = bgColor
				this.ctx.fillRect(0, 0, this.width, this.height)
				this.ctx.draw(true)
			},
			distance(a, b) {
				let x = b.x - a.x;
				let y = b.y - a.y;
				return Math.sqrt(x * x + y * y);
			},
			starts(e) {
				this.line.push({
					points: [{
						time: new Date().getTime(),
						x: e.touches[0].x,
						y: e.touches[0].y,
						dis: 0
					}]
				})
				let currentPoint = {
					x: e.touches[0].x,
					y: e.touches[0].y
				}
				this.currentPoint = currentPoint
				this.drawer(this.line[this.line.length - 1])
			},
			moves(e) {
				let point = {
					x: e.touches[0].x,
					y: e.touches[0].y
				}
				this.lastPoint = this.currentPoint
				this.currentPoint = point
				this.line[this.line.length - 1].points.push({
					time: new Date().getTime(),
					x: e.touches[0].x,
					y: e.touches[0].y,
					dis: this.distance(this.currentPoint, this.lastPoint)
				})
				this.drawer(this.line[this.line.length - 1])
			},
			drawer(item) {
				this.isSign = true
				let x1, x2, y1, y2, len, radius, r, cx, cy, t = 0.5,
					x, y;
				var time = 0;
				if (item.points.length > 2) {
					let lines = item.points[item.points.length - 3];
					let line = item.points[item.points.length - 2];
					let end = item.points[item.points.length - 1];
					x = line.x;
					y = line.y;
					x1 = lines.x;
					y1 = lines.y;
					x2 = end.x;
					y2 = end.y;
					var dis = 0;
					time = (line.time - lines.time) + (end.time - line.time)
					dis = line.dis + lines.dis + end.dis;
					var ctx = this.ctx;
					var or = Math.min(time / dis * this.linePressure + this.lineMin, this.lineMax);
					cx = (x - (Math.pow(1 - t, 2) * x1) - Math.pow(t, 2) * x2) / (2 * t * (1 - t))
					cy = (y - (Math.pow(1 - t, 2) * y1) - Math.pow(t, 2) * y2) / (2 * t * (1 - t))
					ctx.setLineCap('round')
					ctx.beginPath();
					ctx.setStrokeStyle('black')
					ctx.setLineWidth(5)
					ctx.moveTo(x1, y1);
					ctx.quadraticCurveTo(cx, cy, x2, y2);
					ctx.stroke();
					ctx.draw(true)
				}
			},
			clear() {
				this.ctx.clearRect(0, 0, 1000, 1000)
				this.ctx.draw()
				this.drawBgColor()
				this.isSign = false
			},
			save() {
				var that = this;
				if (!this.isSign) {
					return uni.showToast({ title: '请在空白处签字', icon: 'none' })
				}
				uni.canvasToTempFilePath({
					canvasId: 'designature',
					fileType: 'png',
					quality: 1, //图片质量
					success: function(res) {
						// 旋转角度
						that.rotate(res.tempFilePath);
					},
					fail(e) {
						console.log(e)
					}
				}, this)
			},
			//旋转图片
			rotate(tempFilePath) {
				const that = this
				let width = this.height
				let height = this.width
				var ctx = this.ctx2
				ctx.translate(width / 2, height / 2)
				ctx.rotate((270 * Math.PI) / 180)
				ctx.drawImage(tempFilePath, -height / 2, -width / 2, height, width)
				ctx.draw(false, (data) => {
					// 将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中
					uni.canvasToTempFilePath({
						width: width,
						height: height,
						canvasId: 'designature2',
						fileType: 'png',
						quality: 1, //图片质量
						success(res2) {
							uni.uploadFile({
								url: baseURL + '/api/upload',
								filePath: res2.tempFilePath,
								name: 'file',
								formData: {
									key: 'file',
									value: res2.tempFilePath
								},
								header: { 'Content-Type': 'multipart/form-data' },
								success: (uploadFileRes) => {
									let urlObj = JSON.parse(uploadFileRes.data);
									let backObj = {
										param: that.param,
										url: JSON.parse(crypto.decrypt2(urlObj.data))
									}
									uni.$emit('signPopupFinish', backObj)
									that.close()
								},
							})
						}
					}, that)
				});
			},
		}
	}
</script>

<style scoped lang="scss">
	.c-sign {
		display: flex;
		width: 750rpx;
		height: 100vh;
		background: #666666;
		overflow: hidden;
	}

	.opts {
		display: flex;
		flex-direction: column;
		justify-content: flex-end;

		.opts_btn {
			display: flex;
			align-items: center;
			justify-content: center;
			height: 35px;
			font-size: 14px;
			color: #303133;
			background: #bcbcbc;
			border-radius: 4px;
			margin: 20px 0;
			transform: rotate(90deg);
		}

		.opts_btn--confirm {
			color: #fff;
			background: #49b9ac;
		}
	}

	.canvas-wrap {
		flex: 1;
	}

	.canvas {
		background-color: #E6E6E6;
		position: relative;
		z-index: 9999;
	}

	.canvasImg {
		width: 300rpx;
		height: 300rpx;
		position: fixed;
		top: -10000rpx;
		left: 0rpx;
	}
</style>